package com.example.javaproject.spider;

import com.example.javaproject.okhttp.TextUtils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 下载一张图
 */
public class SpiderImageDownloader implements Runnable {
    String url;
    File dir;
    String fileName;

    //"http://f.yhres.com/wm/share_webcastEKZ4BGN2AQD2AJ9bJD/2017/02/08/508252090546562_0.png-q75"
    public SpiderImageDownloader(String url, File dir) {
        if (url.endsWith("-q75")) {
            url = url.substring(0, url.length() - 4);
        }
        this.url = url;
        this.dir = dir;
        fileName = url.substring(url.lastIndexOf("/") + 1);
    }

    @Override
    public void run() {
        dir.mkdirs();
        File destFile = new File(dir, fileName);
        Request builder = new Request.Builder().url(url).build();
        Call call = OkHttpProxy.getInstance().mOkHttpClient.newCall(builder);
        try {
            Response execute = call.execute();
            if (destFile.exists()) {
                try {
                    String header = execute.header("Content-Length");
                    if (!TextUtils.isEmpty(header)) {
                        if (destFile.length() == Long.parseLong(header)) {
                            return;
                        } else {
                            System.out.println("find a  has width and height invalidate file :" + destFile);
                            destFile.delete();
                        }
                    }
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }

            InputStream inputStream = execute.body().byteStream();
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(destFile));
            byte[] buffer = new byte[8 * 1024];
            int len;
            while (-1 != (len = inputStream.read(buffer))) {
                bufferedOutputStream.write(buffer, 0, len);
            }
            inputStream.close();
            bufferedOutputStream.close();
            System.out.println(url + "  downloaded");
        } catch (IOException e) {
            e.printStackTrace();
            destFile.delete();
            System.out.println(url + "  download failed");
        }
    }
}
